//
//  AddAlbumViewController.m
//  iOS-CtrlV
//
//  Created by 龚 杰 on 12-12-28.
//  Copyright (c) 2012年 Wang Li. All rights reserved.
//

#import "AddAlbumViewController.h"
#import "MainTabBarController.h"
#import "NicknameSetViewController.h"
#import "ChooseAlbumViewController.h"
#import "AlbumModel.h"
#import "MyHttpProcessor.h"
#import "WebViewController.h"
#import "SettingViewController.h"

#define BLOGIMAGEPATH [NSString stringWithFormat:@"%@/tmp/blogimage.jpeg",NSHomeDirectory()]
#define ALBUMNAMETEXT @"请选择专辑"
@interface AddAlbumViewController ()

@end

@implementation AddAlbumViewController
@synthesize headimage = m_headimage;
@synthesize user_id = m_user_id;
@synthesize titletext;
@synthesize Albumid = m_Albumid;
@synthesize Albumname = m_Albumname;
@synthesize blogid = m_blogid;
- (id)init
{
    if (self=[super init]) {
        // Custom initialization
        blogtype = SEND_BLOG;
         m_Intype = 0;
        m_Insina = 0;
        m_Inqq = 0;
    }
    return self;
}
- (id)initType:(NSInteger)type
{
    if (self = [super init]) {
        blogtype = type;
        m_Intype = 0;
        m_Insina = 0;
        m_Inqq = 0;
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
   
	// Do any additional setup after loading the view.
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
	// Do any additional setup after loading the view.
    if([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
        [self.navigationController.navigationBar setBackgroundImage:tAppDel.m_MidNavImg forBarMetrics: UIBarMetricsDefault];
        self.navigationController.navigationBar.clipsToBounds = NO;
    }
    m_BackBttBarItem =[UIButton buttonWithType:UIButtonTypeCustom];
    m_BackBttBarItem.frame =CGRectMake(0, 0, 44, 44);
    [m_BackBttBarItem setImage:[UIImage imageNamed:@"navclose.png"] forState:UIControlStateNormal];
    [m_BackBttBarItem addTarget:self action:@selector(navBackBtt) forControlEvents:UIControlEventTouchUpInside];
    [m_BackBttBarItem retain];
    [self.navigationController.navigationBar addSubview:m_BackBttBarItem];
    
    m_settngBttBarItem =[UIButton buttonWithType:UIButtonTypeCustom];
    m_settngBttBarItem.frame =CGRectMake(self.navigationController.navigationBar.frame.size.width-44, 0, 44, 44);
    [m_settngBttBarItem setImage:[UIImage imageNamed:@"navyes.png"] forState:UIControlStateNormal];
    [m_settngBttBarItem addTarget:self action:@selector(navSettingBtt) forControlEvents:UIControlEventTouchUpInside];
    [m_settngBttBarItem retain];
    [self.navigationController.navigationBar addSubview:m_settngBttBarItem];
    
    m_TableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
                                               style:UITableViewStyleGrouped];
    [m_TableView setDataSource:self];
    [m_TableView setDelegate:self];
    UIView* iview = [[UIView alloc] initWithFrame:m_TableView.frame];
    [iview setBackgroundColor:[UIColor colorWithRed:221/250.f green:224/255.0f blue:223/255.0f alpha:1.0]];
    m_TableView.backgroundView =iview;
    [iview release];
    [self.view addSubview:m_TableView];
    
    if (blogtype == SEND_BLOG) {
       self.titletext = @"请输入帖子内容";
    }else{
    }
    NSUserDefaults* tUserDef = [NSUserDefaults standardUserDefaults];
    NSString* nameKey = [NSString stringWithFormat:@"Albumname%@",m_user_id];
    NSString* idKey = [NSString stringWithFormat:@"Albumid%@",m_user_id];
    NSString* str = [tUserDef objectForKey:nameKey];
    NSString* Albumid = [tUserDef objectForKey:idKey];
    if (str == nil||str==@"") {
        m_Albumname = ALBUMNAMETEXT;
    }else{
        m_Albumname = str;
        m_Albumid = Albumid;
    }
    [self deleteImage:BLOGIMAGEPATH];
    [self writeImage:m_headimage toFileAtPath:BLOGIMAGEPATH];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillDisappear:(BOOL)animated
{
    [m_BackBttBarItem removeFromSuperview];
    [m_settngBttBarItem removeFromSuperview];

}
- (void)viewWillAppear:(BOOL)animated
{
    if ([m_BackBttBarItem superview] == nil) {
        [self.navigationController.navigationBar addSubview:m_BackBttBarItem];
    }
    if ([m_settngBttBarItem superview] == nil) {
        [self.navigationController.navigationBar addSubview:m_settngBttBarItem];
    }
    MainTabBarController* tMainTabBar = (MainTabBarController*)self.navigationController.tabBarController;
    [tMainTabBar.m_TabbarCustom removeFromSuperview];
    [self.view addSubview:tMainTabBar.m_TabbarCustom];
}

- (void)navBackBtt
{
    MainTabBarController* tMainTabBar = (MainTabBarController*)self.navigationController.tabBarController;
    tMainTabBar.m_TabbarCustom.hidden =NO;
    if (blogtype == SEND_BLOG) {
        [tMainTabBar CreatePicker];
    }else{
    }
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)navSettingBtt
{

    if ([m_Albumname isEqual:ALBUMNAMETEXT] /*|| [atitle isEqual:@"请输入帖子内容"]*/) {
        AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
        [tAppDel showWithCustomView:@"提示" detailText:@"请选择专辑" isCue:YES delayTime:2.0f];
    }else{
        if (blogtype == SEND_BLOG) {
            if ([m_title.text isEqual:@"请输入帖子内容"]) {
                m_title.text = @"";
            }
            [[MyHttpProcessor sharedManager] RequestHairBlogPost:m_user_id description:m_title.text collect_id:m_Albumid sina:m_Insina tencent:m_Inqq imagepath:BLOGIMAGEPATH];
            [MyHttpProcessor sharedManager].delegate = self;
            [self addHudLoad];
            m_Inqq = 0;
            m_Insina = 0;

        }
        else if(blogtype == FORWARD_BLOG)
        {
            [[MyHttpProcessor sharedManager] RequestTurnminingBlogPost:m_user_id description:m_title.text collect_id:m_Albumid sina:m_Insina tencent:m_Inqq blogid:m_blogid.integerValue];
            [MyHttpProcessor sharedManager].delegate = self;
            [self addHudLoad];
            m_Inqq = 0;
            m_Insina = 0;
        }
    }


}

#pragma mark-
#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            NicknameSetViewController* iNickname = [[NicknameSetViewController alloc] init];
            iNickname.navigationItem.hidesBackButton =YES;
            NSString* str = m_title.text;
            if ([str isEqual:@"请输入帖子内容"]) {
                iNickname.nicktext =@"";
            }else{
                iNickname.nicktext = m_title.text;
            }
            
            MainTabBarController* tMainTabBar = (MainTabBarController*)self.navigationController.tabBarController;
            tMainTabBar.m_TabbarCustom.hidden = YES;
            iNickname.delegate =self;
            [self.navigationController pushViewController:iNickname animated:YES];
            [iNickname release];
        }else{
            ChooseAlbumViewController* ichoosealbum = [[ChooseAlbumViewController alloc] init];
            ichoosealbum.navigationItem.hidesBackButton = YES;
            MainTabBarController* tMainTabBar = (MainTabBarController*)self.navigationController.tabBarController;
            tMainTabBar.m_TabbarCustom.hidden = YES;
            ichoosealbum.delegate = self;
            [self.navigationController pushViewController:ichoosealbum animated:YES];
            [ichoosealbum release];
        }
    }else{
        NSUserDefaults* tUserDef = [NSUserDefaults standardUserDefaults];
        //[tUserDef synchronize];
////        m_userid = [tUserDef stringForKey:@"user_id"].integerValue;
////        UILabel* name = (UILabel*)[m_head viewWithTag:101];
//        name.text = [tUserDef stringForKey:@"nickname"];
////        AsyncImageView* asyimg = (AsyncImageView*)[m_head viewWithTag:100];
////        asyimg._imageRequestURL = [tUserDef stringForKey:@"avatar"];
////        asyimg.m_BoolSetImage = YES;
////        [asyimg customLoadImageFromURL];
        
        SettingViewController* ichoosealbum = [[SettingViewController alloc] init];
        ichoosealbum.name = [tUserDef stringForKey:@"nickname"];
        ichoosealbum.headurl = [tUserDef stringForKey:@"avatar"];
        ichoosealbum.navigationItem.hidesBackButton = YES;
        MainTabBarController* tMainTabBar = (MainTabBarController*)self.navigationController.tabBarController;
        tMainTabBar.m_TabbarCustom.hidden = YES;
        [self.navigationController pushViewController:ichoosealbum animated:YES];
        [ichoosealbum release];
//        if (indexPath.row == 0) {
//            [[MyHttpProcessor sharedManager] RequestInsurgentblog:m_user_id target:@"sina"];
//            [MyHttpProcessor sharedManager].delegate = self;
//            [self addHudLoad];
//            m_Intype =1;
//        }else
//        {
//            [[MyHttpProcessor sharedManager] RequestInsurgentblog:m_user_id target:@"tencent"];
//            [MyHttpProcessor sharedManager].delegate = self;
//             [self addHudLoad];
//            m_Intype = 2;
//        }
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
    }else if(section == 1){
        UIView* tSectionHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 600)];
        [tSectionHeaderView setBackgroundColor:[UIColor colorWithRed:221/250.f green:224/255.0f blue:223/255.0f alpha:1.0]];
        UILabel* tLab = [[UILabel alloc] initWithFrame:CGRectMake(20, 30, 300, 20)];
        [tLab setBackgroundColor:[UIColor clearColor]];
        [tLab setFont:[UIFont systemFontOfSize:16.0f]];
        [tLab setTextColor:[UIColor colorWithRed:125/250.f green:125/255.0f blue:125/255.0f alpha:1.0]];
        [tLab setText:@"分享到"];
        [tSectionHeaderView addSubview:tLab];
        [tLab release];
        return [tSectionHeaderView autorelease];
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }else if(section == 1){
        return 60;
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45;
}
#pragma mark-
#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    static NSString* tSStrCell = @"logincell";
    UITableViewCell* tCell = [tableView dequeueReusableCellWithIdentifier:tSStrCell];
    if (tCell == nil) {
        tCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tSStrCell] autorelease];
        if (section == 0) {
            
            tCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            
            if (row == 0) {
                
                UIImageView* headimage = [[UIImageView alloc] initWithFrame:CGRectMake(15, 5, 35, 35)];
                headimage.tag = 100;
                [headimage setBackgroundColor:[UIColor blackColor]];
                [tCell.contentView addSubview:headimage];
                [headimage release];
                
                m_title = [[UILabel alloc] initWithFrame:CGRectMake(65, 13, tableView.frame.size.width-90, 20)];
                m_title.tag = 99;
                m_title.backgroundColor = [UIColor clearColor];
                m_title.font = [UIFont boldSystemFontOfSize:12.0f];
                m_title.textColor = [UIColor colorWithRed:153.0/255.0f green:153.0/255.0f blue:153.0/255.0f alpha:1.0f];
                [tCell.contentView addSubview:m_title];
                
            }else{
                m_Albumbel = [[UILabel alloc] initWithFrame:CGRectMake(15, 13, tCell.frame.size.width-30, 20)];
                m_Albumbel.tag = 101;
                m_Albumbel.backgroundColor = [UIColor clearColor];
                m_Albumbel.font = [UIFont boldSystemFontOfSize:14.0f];
                m_Albumbel.textColor = [UIColor colorWithRed:153.0/255.0f green:153.0/255.0f blue:153.0/255.0f alpha:1.0f];
                [tCell.contentView addSubview:m_Albumbel];
                [m_Albumbel release];
            }
        }else{
            UILabel* name = [[UILabel alloc] initWithFrame:CGRectMake(15, 12, 150, 20)];
            name.tag = 102;
            name.backgroundColor = [UIColor clearColor];
            name.font = [UIFont boldSystemFontOfSize:15.0f];
            name.textColor = [UIColor colorWithRed:51/255.0f green:51/255.0f blue:51/255.0f alpha:1.0f];
            [tCell.contentView addSubview:name];
            [name release];
        }
    }
    
    if (section == 0) {
        if (row == 0) {
            UIImageView* image = (UIImageView*)[tCell viewWithTag:100];
            [image setImage:m_headimage];
            m_title.text = titletext;
            tCell.accessoryType = UITableViewCellAccessoryNone;//add by Scott
        }else{
            m_Albumbel.text = m_Albumname;
        }
    }
    else
    {
        [tCell.textLabel setFont:[UIFont boldSystemFontOfSize:14]];
        tCell.textLabel.textColor = [UIColor colorWithRed:51/250.f green:51/255.0f blue:51/255.0f alpha:1.0];
        tCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        tCell.selectionStyle = UITableViewCellSelectionStyleGray;
        if (row == 0) {
            UILabel* title = (UILabel*)[tCell viewWithTag:102];
            title.text = @"新浪微博";

        }else{
            UILabel* title = (UILabel*)[tCell viewWithTag:102];
            title.text = @"腾讯微博";

        }
    }
    tCell.backgroundColor = [UIColor whiteColor];
    
    return tCell;
}
#pragma mark-
#pragma mark markNicknameSetDelegate
- (void)GetText:(NSString *)text
{
    self.titletext = text;
    [m_title setText:titletext];
}
- (void)getAlbumInformation:(AlbumModel *)data
{
    if (data!=nil) {
        m_Albumname = data.albumtitle;
        m_Albumid = data.albumid;
        [m_Albumbel setText:m_Albumname];
    }
}

#pragma mark-
#pragma mark MyHttpProcessorDelegate
- (void)OutHairBlogResults:(NSString *)dic
{
    [self hudWasHidden:nil];
    if (dic.intValue == 1) {
        AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
        [tAppDel showWithCustomView:@"提示" detailText:@"发布成功" isCue:NO delayTime:2.0f];
    }
    [self deleteImage:BLOGIMAGEPATH];
    NSUserDefaults* tUserDef = [NSUserDefaults standardUserDefaults];
    NSString* nameKey = [NSString stringWithFormat:@"Albumname%@",m_user_id];
    NSString* idKey = [NSString stringWithFormat:@"Albumid%@",m_user_id];
    [tUserDef setObject:m_Albumname forKey:nameKey];
    [tUserDef setObject:m_Albumid forKey:idKey];
    [self performSelector:@selector(popview) withObject:nil afterDelay:2.5f];
}
- (void)OUtTurnminingBlogResults:(NSString *)dic
{
    [self hudWasHidden:nil];
    if (dic.intValue == 1) {
        AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
        [tAppDel showWithCustomView:@"提示" detailText:@"转采成功" isCue:NO delayTime:2.0f];
    }
    NSUserDefaults* tUserDef = [NSUserDefaults standardUserDefaults];
    NSString* nameKey = [NSString stringWithFormat:@"Albumname%@",m_user_id];
    NSString* idKey = [NSString stringWithFormat:@"Albumid%@",m_user_id];
    [tUserDef setObject:m_Albumname forKey:nameKey];
    [tUserDef setObject:m_Albumid forKey:idKey];
    [self performSelector:@selector(popview) withObject:nil afterDelay:2.5f];
}
- (void)OutInsurgentblog:(NSDictionary *)dic
{
    [self hudWasHidden:nil];
    NSString* result = [dic objectForKey:@"result"];
    if (result.integerValue == 1) {
        AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
        [tAppDel showWithCustomView:@"提示" detailText:@"已经绑定" isCue:YES delayTime:2.0f];
        if (m_Intype == 1) {
            m_Insina = 1;
        }else if(m_Intype == 2){
            m_Inqq = 1;
        }
        m_Intype = 0;
    }else{
        WebViewController* tNextVC = [[WebViewController alloc] init];
        tNextVC.m_CallString = [dic objectForKey:@"callback"];
        tNextVC.m_RequestString =[dic objectForKey:@"auth"];
        tNextVC.navigationItem.hidesBackButton =YES;
        [self.navigationController pushViewController:tNextVC animated:YES];
        [tNextVC release];
    }
}
- (void)OurErrer:(NSDictionary*)dic
{
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [tAppDel showWithCustomView:@"提示" detailText:[dic objectForKey:@"errorMsg"] isCue:YES delayTime:3.0f];
    [self hudWasHidden:nil];
    [self deleteImage:BLOGIMAGEPATH];
}

- (void)popview
{
    MainTabBarController* tMainTabBar = (MainTabBarController*)self.navigationController.tabBarController;
    tMainTabBar.m_TabbarCustom.hidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -
#pragma mark MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud{
    m_MBHUD.delegate = nil;
	[m_MBHUD removeFromSuperview];
	[m_MBHUD release];
	
	m_MBHUD=nil;
}

-(void) addHudLoad{
	if (m_MBHUD == nil) {
		m_MBHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
		// Add HUD to screen
		[self.navigationController.view addSubview:m_MBHUD];
		// Regisete for HUD callbacks so we can remove it from the window at the right time
		m_MBHUD.delegate = self;
		m_MBHUD.labelText = @"请求数据中...";
		[m_MBHUD show:YES];
	}
}

#pragma mark -
#pragma mark writAnddelete
- (BOOL)writeImage:(UIImage*)image toFileAtPath:(NSString*)aPath

{
    
    if ((image == nil) || (aPath == nil) || ([aPath isEqualToString:@""]))
    {
        return NO;
    }
    @try
    
    {
        NSData *imageData = nil;
//        NSString *ext = [aPath pathExtension];
        // the rest, we write to jpeg
        
        // 0. best, 1. lost. about compress.
        
        imageData = UIImageJPEGRepresentation(image, 0);
        
        if ((imageData == nil) || ([imageData length] <= 0))
        {
            return NO;
        }
        [imageData writeToFile:aPath atomically:YES];
        return YES;
    }
    @catch (NSException *e)
    
    {
        NSLog(@"create thumbnail exception.");
        
    }
    return NO;
}

- (BOOL)deleteImage:(NSString*)aPath
{
    if ((aPath == nil) || ([aPath isEqualToString:@""]))
    {
        return NO;
    }
	NSFileManager *fm = [NSFileManager defaultManager];
	NSError *error;
    if (![fm fileExistsAtPath:aPath]) {
        return NO;
    }
	if(![fm removeItemAtPath:aPath error:&error])
	{
		NSLog(@"%@ can not be removed because:%@", aPath, error);
        return NO;
	}else{
        return YES;
    }
}
- (void)dealloc
{
   [titletext release];
    m_BackBttBarItem = nil;
    m_settngBttBarItem = nil;
    [m_TableView release];
    [m_title release];
    m_MBHUD = nil;

    self.headimage = nil;
    
    [super dealloc];
}
@end
